//
//  SearchViewController.m
//  MMLOOK
//
//  Created by dllo on 15/9/3.
//  Copyright (c) 2015年 武俊娥. All rights reserved.
//

#import "SearchViewController.h"
#import "NSDictionary+mutableDeepCopy.h"

@interface SearchViewController ()

@end

@implementation SearchViewController

- (void)dealloc
{
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatSearch];
    self.view.backgroundColor = [UIColor cyanColor];
    [self creatTable];
    //////
    /*加载plist文件*/
    NSString *wordsPath = [[NSBundle mainBundle]pathForResource:@"NoteSection" ofType:@"plist"];//得到属性列表的路径
    NSDictionary *dictionary = [[NSDictionary alloc]initWithContentsOfFile:wordsPath];
    self.allWords = dictionary;
    [self resetSearch]; //加载并填充words可变字典和keys数组
    
    _search.autocapitalizationType = UITextAutocapitalizationTypeNone;//不自动大写
    _search.autocorrectionType = UITextAutocorrectionTypeNo;//不自动纠错
    
    
}

- (void)creatTable
{
    self.table = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain] autorelease];
    _table.dataSource = self;
    _table.delegate = self;
    [self.view addSubview:_table];
}

//取消搜索或者改变搜索条件
- (void)resetSearch
{
    self.words = [self.allWords mutableDeepCopy]; //得到所有字典的副本 得到一个字典
    NSLog(@"所有字典 = %@",self.words);
    NSMutableArray *keyArray = [[NSMutableArray alloc]init];//创建一个可变数组
    [keyArray addObjectsFromArray:[[self.allWords allKeys]sortedArrayUsingSelector:@selector(compare:)]]; //用指定的selector对array的元素进行排序
    self.keys = keyArray; //将所有key 存到一个数组里面
    NSLog(@"所有key = %@",self.keys);
}
//实现搜索方法
- (void)handleSearchForTerm:(NSString *)searchTerm
{
    NSMutableArray *sectionsRemove = [[NSMutableArray alloc]init]; //创建一个数组存放我们所找到的空分区
    [self resetSearch];
    for(NSString *key in self.keys)//遍历所有的key
    {
        NSMutableArray *array = [_words valueForKey:key] ;     //得到当前键key的名称 数组
        NSMutableArray *toRemove = [[NSMutableArray alloc]init];//需要从words中删除的值 数组
        for(NSString *word in array) //实现搜索
        {
            if([word rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound)//搜索时忽略大小写 把没有搜到的值 放到要删除的对象数组中去
                [toRemove addObject:word]; //把没有搜到的内容放到 toRemove中去
        }
        
        if([array count] == [toRemove count])//校对要删除的名称数组长度和名称数组长度是否相等
            [sectionsRemove addObject:key]; //相等 则整个分区组为空
        [array removeObjectsInArray:toRemove]; //否则 删除数组中所有与数组toRemove包含相同的元素
    }
    [self.keys removeObjectsInArray:sectionsRemove];// 删除整个key 也就是删除空分区，释放用来存储分区的数组，并重新加载table 这样就实现了搜索
    [_table reloadData];
}

- (void)viewWillAppear:(BOOL)animated //当使用Push或者prenset方式调用
{
}
//#pragma mark -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return ([_keys count] >0)?[_keys count]:1; //搜索时可能会删除所有分区 则要保证要有一个分区
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([_keys count] == 0)
    {
        return 0;
    }
    NSString *key = [_keys objectAtIndex:section]; //得到第几组的key
    NSArray *wordSection = [_words objectForKey:key]; //得到这个key里面所有的元素
    return [wordSection count]; //返回元素的个数
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = [indexPath section]; //得到第几组
    NSUInteger row = [indexPath row]; //得到第几行
    NSString *key = [_keys objectAtIndex:section]; //得到第几组的key
    NSArray *wordSection = [_words objectForKey:key]; //得到这个key里面的所有元素
    static NSString *NoteSectionIdentifier = @"NoteSectionIdentifier";
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:NoteSectionIdentifier];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NoteSectionIdentifier];
        
    }
    cell.textLabel.text = [wordSection objectAtIndex:row];
    return cell;
}
//为每个分区指定一个标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if([_keys count] == 0)
        return @" ";
    NSString *key = [_keys objectAtIndex:section];
    return key;
}
//创建一个索引表
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return _keys;
}
#pragma mark -

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_search resignFirstResponder]; //点击任意 cell都会取消键盘
    return indexPath;
}

#pragma mark-

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar //搜索button点击事件
{
    NSString *searchTerm = [searchBar text];
    [self handleSearchForTerm:searchTerm]; //搜索内容 删除words里面的空分区和不匹配内容
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{   //搜索内容随着输入及时地显示出来
    if([searchText length] == 0)
    {
        [self resetSearch];
        [_table reloadData];
        return;
    }
    else
        [self handleSearchForTerm:searchText];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar //点击取消按钮
{
    _search.text = @"";  //标题 为空
    [self resetSearch]; //重新 加载分类数据
    [_table reloadData];
    [searchBar resignFirstResponder]; //退出键盘
    
}

- (void)creatSearch
{
    self.search = [[[UISearchBar alloc] initWithFrame:CGRectMake(30, 70, 250, 30)] autorelease];
    self.search.layer.borderWidth = 1;
    self.search.backgroundColor = [UIColor blackColor];
    self.search.placeholder = @"搜索";
    self.search.layer.cornerRadius = 14;
    [self.table addSubview:_search];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
